<template>
    <div>
        <div class="setdown" >
            <div class="d-outer"
                 v-for="item in members"
                 :key="item.avatarUrl">
                <img class="inner"
                     :src="item.avatarUrl" />
            </div>

        </div>
        <button type="primary"
                @click="start_game">开始游戏</button>
        <button open-type='share'>邀请好友</button>

        <div class="house-tip">
            <div>房号：<text class="house_id">{{house_id}}</text></div>
            <!-- <div>房主：<text>{{house_info.name}}</text></div> -->
            <div>计分规则：<text>进行游戏，猜中+3分，画对+1分</text></div>
            <div>注意：<text>坐下后尽量不要离开,可直接分享给好友或者告知朋友在微信小程序中搜索(你画我猜艾吧)进入后搜索房号进入房间</text></div>
        </div>
        <div class="container"
             v-if="spinShow">
            <i-spin fix></i-spin>
        </div>
        <i-message id="message" />
        <get-user-info-model :hide-get-user-info-model="hide_getUserInfo_model"
                             @agree="agree"
                             @cancle="cancle" />
    </div>
</template>

<script>
import store from '../../store';
// getCurrentPageParams,
import { getCurrentPageParams, getCurrentPageUrl } from '../../utils';
const { $Message } = require('../../../static/iview/base/index');

export default {
    data() {
        return {
            timerId: '',
            house_id: '',
            alreadyInit: false, // 只初始化a一次ws
            members: {},
            spinShow: false,
            // wsOpenSuccess: false, // ws是否注册监听了事件
            hide_getUserInfo_model: true,
            wait_task_arr: [] // 被打断待执行的函数
        };
    },

    computed: {
        G() {
            return store.state.globalData;
        },
        socketOpen() {
            return store.state.globalData.WS.socketOpen
        }
    },
    watch: {
        socketOpen(newV) {
            const url = getCurrentPageUrl();
            if (url === 'pages/ready/main') {
                // !this.wsOpenSuccess &&
                if (newV) {
                    // 只需执行一次，防止多次注册ws事件
                    this.wsOpenSuccess = true;
                    this.initWs()
                }
            }
        }
    },
    methods: {

        async agree(res) {
            this.hide_getUserInfo_model = true;
            if (res.detail.detail.errMsg === 'getUserInfo:ok') {
                await store.dispatch('get_info');
                // await app.get_info();
                this.wait_task_arr.forEach(value => {
                    this[value]();
                });
                this.wait_task_arr = [];
                this.spinShow = false;
            } else {
                wx.redirectTo({
                    url: `../index/main`
                });
            }
        },
        check_info() {
            return new Promise((resolve, reject) => {
                wx.getSetting({
                    success: async res => {
                        if (res.authSetting['scope.userInfo']) {
                        // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                            if (!this.G.userInfo || !this.G.openid) {
                                await store.dispatch('get_info');
                                this.wait_task_arr.forEach(value => {
                                    this[value]();
                                });
                                this.wait_task_arr = [];
                                resolve();
                            }
                        } else {
                            this.hide_getUserInfo_model = false;

                            resolve();
                        }
                    }
                });
            });
        },
        cancle() {
            this.spinShow = false;
            this.hide_getUserInfo_model = true;
            wx.redirectTo({
                url: `../index/main`
            });
        },

        // 获取房间信息。
        send_on_line() {
            const data = {
                type: 'join_house',
                data: {
                    house_id: this.house_id,
                    openid: this.G.openid,
                    name: this.G.userInfo.nickName,
                    avatarUrl: this.G.userInfo.avatarUrl,
                    gender: this.G.userInfo.gender
                }
            };
            store.dispatch('sendSocketMessage', data);
        },
        start_game() {
            if (Object.keys(this.members).length < 2) {
                wx.showToast({
                    title: '游戏人数不足',
                    icon: 'none',
                    duration: 2000 // 持续的时间
                });
            } else {
                store.dispatch('sendSocketMessage', {
                    type: 'game_begin',
                    data: {
                        house_id: this.house_id
                    }
                });

                wx.showLoading({
                    title: '准备开始...'
                });
            }
        },

        initCheck() {
            if (this.G.userInfo && this.G.openid) {
            // && !this.wsOpenSuccess
                if (this.socketOpen) {
                // 只需执行一次，防止ws还没开启就执行了注册监听事件
                // this.wsOpenSuccess = true;
                    this.initWs();
                    setTimeout(() => { console.log(11111);this.initWs(); }, 2000)
                }
                this.send_on_line();
            } else {
                const arr = Object.assign([], this.wait_task_arr);
                arr.push('initCheck');
                this.wait_task_arr = arr;

                this.check_info();
            }
        },

        initWs() {
            console.log('initWsReady')
            wx.onSocketMessage(ret => {
                console.log('onSocketMessage-Ready')
                if (
                    Object.keys(this.members).length < 1 &&
                    this.G.userInfo &&
                    this.G.openid
                ) {
                    console.log('重新请求成员信息');
                    // 写这个判断是因为经常进入页面户ws监听的还没来得及收到消息导致页面上没有头像
                    this.send_on_line();
                }
                const url = getCurrentPageUrl();
                if (url !== 'pages/ready/main') {
                    return;
                }
                const res = JSON.parse(ret.data);
                if (res.type === 'ready_members') {
                    this.spinShow = false;
                    console.log(this.spinShow, 'this.spinShow')
                    this.members = res.data.members;
                }
                if (res.type === 'game_begin') {
                // 开始游戏
                    wx.redirectTo({
                        url: `../ongoing/main?house_id=${this.house_id}`
                    });
                }
                if (res.type === 'house_err') {
                    $Message({
                        content: res.data || '错误',
                        type: 'error',
                        duration: 2 // 持续的时间
                    });
                    setTimeout(() => {
                        wx.redirectTo({
                            url: `../index/main`
                        });
                    }, 2000);
                }
                console.log('收到服务器内容ready.js：' + ret.data);
            });
            // 在本页面定期发送心跳
            this.timerId = setInterval(() => {
                store.dispatch('sendSocketMessage', {
                    type: 'ping',
                    data: {
                        openid: this.G.openid,
                        house_id: this.house_id
                    }
                });
            }, 5000);
        }
    },
    onShow() {
        console.log('onshowReady')
        const urlParams = getCurrentPageParams();
        this.house_id = urlParams.house_id;
        this.spinShow = true;
        this.initCheck();
    },
    onShareAppMessage(res) {
        return {
            title: '快来和我玩你画我猜',
            path: '/pages/ready/main?house_id=' + this.house_id + '&from=share'
        };
    },
    onUnload() {
        clearInterval(this.timerId);
    },
    // 捕获 app error
    onError(err) {
        console.log('ongoing-error:' + err);
    }
};
</script>

<style scoped>
button {
  line-height: 80rpx;
}
.setdown {
  margin: 20px auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.setdown .d-outer {
  width: 80px;
  height: 80px;
  text-align: center;
  margin: 10px 0;
}
.setdown .inner {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin: 0 auto;
  /* background: #e64340;
	color:#fff;

	overflow: hidden;
	white-space:nowrap;
	overflow:hidden;
	text-overflow:ellipsis; */
}
button {
  width: 80%;
  height: 40px;
  margin-top: 15px;
}
.create-house {
  margin: 20px;
}
.house-tip {
  width: 80%;
  margin: 10px auto;
  color: #353535;
}
.house-tip text {
  font-size: 14px;
}
.house-tip .house_id {
  color: red;
  font-size: 18px;
}
</style>
